package com.zzw.initializer;

import com.zzw.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

/**
 * 自定义web应用初始化器
 * 作用：基于代码实现web.xml配置，可以将监听器、过滤器、servlet注册的web容器中
 * @Author: zhangzhiwei
 * @Date: 2022/1/4 0:06
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {

	Logger log = LoggerFactory.getLogger(MySpringServletContainerInitializer.class);

	public MyWebApplicationInitializer() {
	}

	public void onStartup(ServletContext servletContext) throws ServletException {
		// Load Spring web application configuration
		//通过注解的方式初始化Spring的上下文
		AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
		//注册spring的配置类（替代传统项目中xml的configuration）
		ac.register(AppConfig.class);
		ac.refresh();

		// Create and register the DispatcherServlet
		//基于java代码的方式初始化DispatcherServlet
		DispatcherServlet servlet = new DispatcherServlet(ac);
		ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
		if (registration == null) {
			return;
		}
		registration.setLoadOnStartup(1);
		registration.addMapping("/*");

		// 设置编码过滤器
		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter("UTF-8");
		FilterRegistration.Dynamic encoding = servletContext.addFilter("encoding", characterEncodingFilter);
		if (encoding == null) {
			return;
		}
		encoding.setInitParameter("encoding", "UTF-8");
		encoding.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
	}
}
